package com.farm.common.util;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.experimental.UtilityClass;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 分页参数提取工具
 */
@UtilityClass
public class PageParaUtils {

	/**
	 * 分页参数提取方法
	 *
	 * @param obj 属性包含分页参数的类
	 * @return Page mybatis分页参数
	 */
	public Page withdrawPageByParamName(Object obj) {
		try {
			Page page = new Page(1, 10);
			Class<PageParaPO> pageParaPOClass = PageParaPO.class;
			// 名称获取属性方法，对属性命名有要求，如果命名非默认抛出NoSuchMethodException
			Method method = obj.getClass().getMethod("getPageParaPO");
			return getPage(obj, page, pageParaPOClass, method);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException("参数命名不合法");
		} catch (IllegalAccessException | InvocationTargetException e) {
			throw new RuntimeException("方法无法访问");
		}
	}

	/**
	 * 分页参数提取方法
	 *
	 * @param obj 属性包含分页参数的类
	 * @return Page mybatis分页参数
	 */
	public Page withdrawPageByParamType(Object obj) {
		try {
			Page page = new Page(1, 10);
			Class<PageParaPO> pageParaPOClass = PageParaPO.class;
			// 类型获取属性方法，需要循环，属性名可变，
			Method[] methods = obj.getClass().getMethods();
			Method method = null;
			for (Method m : methods) {
				if (ObjectUtil.equal(m.getReturnType(), pageParaPOClass)) {
					method = m;
					break;
				}
			}
			if (method == null) {
				throw new RuntimeException("参数不包含分页属性");
			}
			return getPage(obj, page, pageParaPOClass, method);

		} catch (IllegalAccessException e) {
			// obj可能非public修饰
			throw new RuntimeException("参数类不允许访问");
		} catch (InvocationTargetException e) {
			// 调用get方法报错且未被捕获

			throw new RuntimeException("获取分页属性失败");
		}
	}

	private Page getPage(Object obj, Page page, Class<PageParaPO> pageParaPOClass, Method method) throws IllegalAccessException, InvocationTargetException {
		Object returnObj = method.invoke(obj);
		PageParaPO pageParaPO = pageParaPOClass.cast(returnObj);
		if (ObjectUtil.isNotEmpty(pageParaPO)) {
			if (ObjectUtil.isNotEmpty(pageParaPO.getCurrent())) {
				page.setCurrent(pageParaPO.getCurrent());
			}
			// -1为获取全部数据
			if (ObjectUtil.isNotEmpty(pageParaPO.getSize()) && (pageParaPO.getSize() > 0 || pageParaPO.getSize() == -1)) {
				page.setSize(pageParaPO.getSize());
			}
		}
		return page;
	}
}

